const app = getApp();
Component({
  data: {
    showAction: false,
    bannerImg: app.getImgUrl('customer-management-banner.png'),
    sortOptions: [
      { text: '时间', value: 'time' },
      { text: '按年', value: 'year' },
      { text: '按月', value: 'month' },
      { text: '名称', value: 'name' }
    ],
    customerList: [],
    currentPhone: '',
    actions: [
      { name: '查看', action: 'view' },
      { name: '编辑', action: 'edit' },
      { name: '删除', action: 'delete', color: "#ee0a24", },
    ],
    selectdItem: {}
  },
  lifetimes: {
    attached() {
      this.getCustomerList();
    }
  },
  methods: {
    onAddCustomer() {
      // 跳转到添加客户页面
      wx.navigateTo({
        url: '/pages/operation-center/add-customer/index'
      });
    },
    onCall(e) {
      const phones = e.currentTarget.dataset.phones;
      const phone = phones.split(',')[0]
      this.setData({
        currentPhone: phone
      })
      const alert = this.selectComponent('#v-alert')
      alert.toggleAlert()
    },
    handleMakeCall() {
      let phoneNumber = this.data.currentPhone
      if (!phoneNumber) return;
      wx.makePhoneCall({
        phoneNumber: phoneNumber,
        success: () => console.log('拨号界面已调起'),
        fail: (err) => console.error('拨号失败', err)
      });
    },
    onCustomerTap(e) {
      const id = e.currentTarget.dataset.item.id;
      wx.navigateTo({
        url: `/pages/operation-center/customer-detail/index?id=${id}`
      });
    },
    getCustomerList() {
      app.axios('customer', {
        op: "ajaxCustomerList",
        page: 1
      }).then(res => {
        if (res.code) {
          const formattedList = res.lists.map(item => {
            // 时间戳转日期（示例中addtime为1727424241）
            const addDate = new Date(item.addtime * 1000);
            const formattedDate = `${addDate.getFullYear()}-${(addDate.getMonth() + 1).toString().padStart(2, '0')}-${addDate.getDate().toString().padStart(2, '0')}`;

            // 重组数据结构
            return {
              id: parseInt(item.id), // 转数字类型
              avatar: item.name ? item.name.charAt(0) : '', // 取名称首字符
              name: item.name || '未命名',
              desc: `${item.addname || '管理员'} ${formattedDate} 添加`,
              icon: app.getImgUrl('phone.png'), // 固定路径或动态配置
              phones: item.phones
            };
          });
          this.setData({
            customerList: formattedList
          })
        }
      })
    },
    onStaffPress(e) {
      console.log(e)
      this.setData({
        showAction: true,
        selectdItem: e.currentTarget.dataset.item
      })
      return false
    },
    onSelect(e) {
      const id = this.data.selectdItem.id;
      this.setData({
        showAction: false,
      })
      if (e.detail.action == 'edit') {
        app.navigateTo(`/pages/operation-center/add-customer/index?id=${id}`)
      } else if (e.detail.action == 'view') {
        app.navigateTo(`/pages/operation-center/customer-detail/index?id=${id}`)
      } else if (e.detail.action == 'delete') {
        const alert = this.selectComponent('#v-alert-delete')
        alert.toggleAlert()
      }
    },
    onSelectClose(e) {
      this.setData({ showAction: false });
    },
    handleDelete() {
      const item = this.data.selectdItem
      app.axios('customer', {
        op: 'ajaxCustomerDel',
        id: item.id,
      }).then(res => {
        if (res.code) {
          wx.showToast({ title: '删除成功' })
          setTimeout(() => {
            this.getCustomerList()
          }, 500);
        }
      })

    }
  }
})